package com.lxq.market.service;

import com.lxq.market.model.User;
import com.lxq.market.util.JDBCUtil;
import com.lxq.market.util.ResultSetConvert;

import java.sql.ResultSet;
import java.util.List;
import java.util.Random;

public class UserService {

    private static UserService userService=new UserService();

    public static UserService getInstance() {
        return userService;
    }

    public boolean addUser(User user){
        user.setUserAccount(randomAccount());
        user.setUserPosition("搬运工");
        return JDBCUtil.execSQL("insert into user values(?,?,?,?,null)", user.getUserAccount(), user.getUserName(),
                user.getUserPassword(), "搬运工");
    }

    public User getUser(String account){
        ResultSet resultSet = JDBCUtil.execQuery("select * from user where user_account=?", account);
        return ResultSetConvert.getInstance().convertOne(resultSet, User.class);
    }

    public boolean delete(String account){
        return JDBCUtil.execSQL("delete from user where user_account=?", account);
    }

    public List<User> findAll(){
        return ResultSetConvert.getInstance().convert(JDBCUtil.execQuery("select * from user"),User.class);
    }

    public boolean updateUserInfo(User user){
        return JDBCUtil.execSQL("update user set user_account=?,user_name=?,user_password=?,user_position=?,user_avatar=? " +
                "where user_account=?",user.getUserAccount(),user.getUserName(),user.getUserPassword(),user.getUserPosition(),
                user.getUserAvatar(),user.getUserAccount());
    }

    public boolean updateUserInfoForAdmin(User user){
        return JDBCUtil.execSQL("update user set user_name=?,user_password=?,user_position=? " +
                        "where user_account=?",user.getUserName(),user.getUserPassword(),user.getUserPosition(),user.getUserAccount());
    }

    private String randomAccount(){
        Random random=new Random();
        return random.nextInt(999)+""+random.nextInt(999)+random.nextInt(999);
    }
}
